import {
  api,
  util,
  storage,
  dialog,
  forms,
  clickIncrement,
  clearIncrement,
  getSign
} from '../../../js/util';
import {
  router
} from '../../../js/router';
import {
  cart,
  order
} from '../../../js/modules/order';
import {
  list,
  detail,
  mall,
  scant
} from '../../../js/modules/mall';
import { 
  activities
} from '../../../js/modules/market';
import {
  GoodsNumCache
} from '../../../js/modules/propertycache.js'
import {
  address
} from '../../../js/modules/store';
import {
  theme
} from '../../../js/modules/theme';
import authorize from '../../../js/modules/authorize';
const info = require("../../../js/modules/info.js");
const componentBehavior = require('../../../js/common/ComponentBehavior')

import {
  category
} from "../../../js/modules/gloab";
import { debounce, getSystemInfoSync, deepClone, isEmpty } from '../../../js/newUtil';
const app = getApp()

/**
 * 虚拟data
 * 原来setData的改为unrealData.setData，防止数据过多白屏
 */
class UnrealData {
  constructor () {
    this.goodsList = [] // 商品列表
    this.cacheData = {} // 缓存
    this.range = 200 // 最多显示多少数据
    this.loadItem = 100 // 加载上一页/下一页数据的偏移量
    this.upperThreshold = 200 // 距离顶部多远时加载上一页数据
    this.listOpacity = 1
  }
  setData (options = {}) {
    for (let i in options) {
      this[i] = options[i]
    }
  }
  reset() {
    this.goodsList = []
    this.cacheData = {}
  }
  /**
   * 页面滚动到顶部，拉去之前的数据
   */
  onPageScroll (scrollTop = 0, that = {}) {
    if (scrollTop >= this.upperThreshold) {
      return
    }
    let list1 = that.data.goodsList
    let list2 = this.goodsList
    let listOpacity = this.listOpacity
    if (isEmpty(list1[0])) {
      return
    }
    if (list1[0].longListIndex == list2[0].longListIndex) {
      console.log('当前为顶部')
    } else {
      let loadItem = this.loadItem
      let start = 0
      let end = this.range
      if (list1[0].longListIndex > loadItem) {
        start = list1[0].longListIndex - loadItem
        end = start + this.range
      }
      let query = wx.createSelectorQuery()
      let selector = `#productlist >>> #long_${list1[0].longListIndex}`
      query.select(selector).fields({
        rect: true
      }).exec((res) => {
        console.log(res)
        let offsetTop = 0
        let duration = 0
        if (!res[0]) {
          listOpacity = 1
        }
        that.setData({
          goodsList: list2.slice(start, end),
          isLoadComplete: true,
          listOpacity
        }, function () {
          if (!res[0]) {
            that.setData({
              listOpacity: 1
            })
            return
          }
          offsetTop = res[0].top
          offsetTop = -offsetTop
          wx.pageScrollTo({
            selector,
            offsetTop,
            duration,
            complete () {
              that.setData({
                listOpacity: 1
              })
            }
          })
        })
      })
    }
  }
  /**
   * 判断是否为页面底部 
   */
  isBottom (that = {}) {
    let list1 = that.data.goodsList
    let list2 = this.goodsList
    if (isEmpty(list1)) {
      return true
    }
    let item1 = list1[list1.length - 1]
    let item2 = list2[list2.length - 1]
    if (isEmpty(item1.longListIndex) || isEmpty(item2.longListIndex)) {
      return true
    }
    if (item1.longListIndex == item2.longListIndex) {
      return true
    }
    return false
  }
  /**
   * 如果goodsList没到底部，则页面再加上loadItem条数据
   * @param pageNeedScroll 是否需要页面滚动到指定位置，当为第一页时无需滚动
   */
  onReachBottom (that = {}, pageNeedScroll = true) {
    let list1 = that.data.goodsList
    let list2 = this.goodsList
    let listOpacity = this.listOpacity
    let item1 = list1[list1.length - 1]
    let end = 50
    let selector = ''
    if (!isEmpty(item1)) {
      end = item1.longListIndex + this.loadItem
      selector = `#productlist >>> #long_${item1.longListIndex}`
    }
    if (end > list2.length) {
      end = list2.length
    }
    let start = end - this.range
    if (start < 0) {
      start = 0
    }
    let query = wx.createSelectorQuery()
    query.select(selector).fields({
      rect: true
    }).exec((res) => {
      console.log(res)
      let offsetTop = 0
      let duration = 0
      if (!res[0]) {
        listOpacity = 1
      }
      that.setData({
        goodsList: list2.slice(start, end),
        isLoadComplete: true,
        listOpacity
      }, function () {
        // 当没有节点无需滚动
        if (!res[0]) {
          that.setData({
            listOpacity: 1
          })
          return
        }
        // 当为第一次加载数据时无需滚动
        if (!pageNeedScroll && (list1.length == 0 || list1.length == list2.length)) {
          that.setData({
            listOpacity: 1
          })
          return
        }
        offsetTop = res[0].top
        offsetTop = -offsetTop
        wx.pageScrollTo({
          selector,
          offsetTop,
          duration,
        })
        that.setData({
          listOpacity: 1
        })
      })
    })
  }
  /**
   * @param pageNeedScroll 是否需要页面滚动到指定位置，当为第一页时无需滚动
   */
  latestData (that = {}, pageNeedScroll = true) {
    this.onReachBottom(that, pageNeedScroll)
  }
  /**
   * 刷新数据 
   */
  refreshGoodsList (that = {}) {
    let list1 = that.data.goodsList
    let list2 = this.goodsList
    let item1 = list1[0]
    if (isEmpty(item1)) {
      return
    }
    list1 = list2.slice(item1.longListIndex, item1.longListIndex + list1.length)
    that.setData({
      goodsList: list1
    })
  }
}
const unrealData = new UnrealData()

Component({
  behaviors: [componentBehavior],
  lifetimes: {
    attached() {
      this.filterComponent = this.selectComponent("#filterComponent")
      // 在组件实例进入页面节点树时执行
      this.fasterComponent = this.selectComponent("#fasterComponent");
      this.outofstock = this.selectComponent("#outofstock");
      this.deliveryComponent = this.selectComponent("#deliveryComponent");
      this.stockdistribution = this.selectComponent("#stockdistribution");
      this.setAsideViewInfo()
    },
    detached() {
      // 在组件实例被从页面节点树移除时执行
      unrealData.reset()
    },
  },
  pageLifetimes: {
    show () {
      this.setLineMode()
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    hasNav: {
      value: false,
      type: Boolean
    },
    hasMaket: {
      value: false,
      type: Boolean
    },
    marketSource: {
      value: {},
      type: Object
    },
    inFast: {
      value: false,
      type: Boolean
    },
    showSwitch:{
      value:false,
      type:Boolean
    },
    btnFoot:{
      value:false,
      type:Boolean
    },
    showChoose:{
      value:false,
      type:Boolean
    },
    showStyle:{
      value:"line",
      type:String
    },
    isScanty: {
      value:false,
      type:Boolean,
      observer(newVal) {
        if (!this.data.enableZeroStockBuy&&this.data.isScanty){
          this.setData({
            isShowZeroStock:1
          })
        }
        else if (!this.data.enableZeroStockBuy && !this.data.isScanty){
          this.setData({
            isShowZeroStock: 0
          })
        }

      }
    },
    enableZeroStockBuy: {
      value: false,
      type: Boolean
    },
    quantityDigits: {
      value: 0,
      type: Number
    },
    priceDigits:{
      value: 2,
      type: Number
    },
    decimalDigits: {
      value: 2,
      type: Number
    },
    showRetailPrice:{
      value:false,
      type:Boolean
    },
    spectStyle:{
      value:0,
      type:Number
    },
    addressAssignDepot:{
      value:false,
      type:Boolean
    },
    GoodsUnitDisplayMode:{
      value:0,
      type:Number
    },
    mainColor:String,
    Currency:String,
    NoLoginShowPrice:Boolean,
    isLogin:Boolean,
    isIphoneX:Boolean,
    isSkip:Boolean,
    CartName:String,
    FieldDisplayName:Array,
    ClassDisplayField:Object,
    listState:Boolean,
    cids:String,
    types:String,
    listType:Boolean,
    scan:Boolean,
    isScan:Boolean,
    show:String,
    position:Boolean, // 是否需要采用粘性布局,使得搜索和排序在顶部固定,促销详情页面使用
    ShowVendorName:Boolean,
    FrontShowStockDetail:Boolean,
    hideActivity: { // 隐藏活动相关内容（拼团、预售、特价、促销活动）
      type: Boolean,
      value: false
    },
    NotShowProductNoneOffered: { // 不显示无货商品按钮
      type: Boolean,
      value: false
    },
    AppQuickTemplateConfig: { // 商品目录样式
      type: Object,
      value: {},
    },
  },

  observers: {
    'AppQuickTemplateConfig,tree,activeOneCategory,activeTwoCategory' () {
      this.setAsideViewInfo()
    },
    'hasNav' () {
      this.setLineMode()
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    PageIndex: 1,
    PageSize: 20,
    imgDomain: api.imgDomain,
    enableOss: api.enableOss,
    sortField: "sortorder",
    sortDirect: "desc",
    vid:'',
    bid: "",//品牌
    tag:"",//商品标签
    cid: 0,//分类
    typeId: 0,//类型
    rule_id: 0, //优惠券规则id
    tag_id:0,//标签id
    ikcqr: '',
    isShowZeroStock: 0,//是否显示零库存
    keywords: "",
    showStyle: 'line',
    hasMoreData: true,
    isLoadComplete: false,
    goodsList: [],
    nowGoodsId: 0,
    scantyProduct: [],
    priceRange: [],
    is_search: false,
    tree: null,
    time:null,
    isLogin:false,
    showFilter: false, //是否显示筛选
    cacheData:{},
    proprietorId:0,
    extattrs:"",
    minprice:"",
    addr:{area:"",code:""},
    thumb:300,
    Currency:app.globalData.Currency,//货币符号
    customAttrs:'',//自定义
    minToPrice:'',//
    listOpacity: 1, // 商品列表显示
    oneCategoryExpand: false, // 一级目录是否展开显示
    threeCategoryExpand: false, // 三级目录是否展开显示
    style: {
      searchTop: 0, // 搜索栏距离顶部的距离
      asideHeight: 1200, // 侧边栏高度
      asideTop: 200, // 侧边栏距离顶部的距离
      contentPaddingTop: 190, // 商品内容区距离顶部距离
      topExpandHeight: 800, // 横向一级分类展开时的高度
      subExpandHeight: 600, // 横向三级分类展开时的高度
    },
    activeOneCategory: -1, // 当前活动的一级分类
    activeTwoCategory: -1, // 当前活动的二级分类
    activeThreeCategory: -1, // 当前活动的三级分类
    categoryIconList: [], // 一级分类图标列表
    isChangeSearchCriteria: false, // 是否已经修改过搜索条件（如修改分类，标签，品牌等）
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**获得签名 */
    getSiginData() {
      let param = this.get_param();
      delete param.PageIndex;
      return getSign(param);
    },
    /**
     * 加载入口
     * 
     */
    loadMain() {
      var that = this;
      //判断是否登录
      if (app.dns.proprietorId == 0 && !authorize.isLogin('store')) {
        authorize.redirect('store');
        return;
      }
      //是否处于搜索模式
      if (that.data.is_search) {
        that.data.is_search = false;
        //如果条件没有发生变化不进行加载
        var sigin = this.getSiginData();
        if (sigin == that.data.sigin) {
          if (that.data.time&&GoodsNumCache.compareTime(that.data.time))          {
            let {
              goodsList
            } = unrealData
            for (var i = 0; i < goodsList.length;i++){
              goodsList[i].CartCount = GoodsNumCache.getProductNum(goodsList[i].ProductId, goodsList[i].CartCount,goodsList[i].IsSingle==1);
            }
            unrealData.setData({
              goodsList
            })
            that.setData({
              goodsList: goodsList,
              isLoadComplete: true,
              isLogin: authorize.isLogin('store'),
              typeId:that.data.types,
            });
          }
          //重新加载标签
          let {
            goodsList
          } = unrealData
          that.loadProductActivities(that, goodsList, 0);
          return;
          }
      }
      that.setData({
        PageIndex: 1,
        keywords: that.data.keywords,
        isLogin: authorize.isLogin('store')
      });
      if (this.data.addressAssignDepot){
        this.deliveryComponent.getDefaultAddress();
      }
      else{
        this.selectedAdress({detail:{Area:"",Code:""}})
      }
      this.loadFirstCategory();
      this.filterComponent.get_category_screens();
    },
    /**
   * 加载类别 
   * */
    loadFirstCategory() {
      if(!this.data.listType)return
      let entity = authorize.getEntity();
      let fkId = 0;
      if (entity) {
        fkId = entity.fkId;
      }
      this.data.fkId = fkId;
      if (this.data.tabKey != "category_" + app.dns.proprietorId + "_" + fkId) {
        this.data.tabKey = "category_" + app.dns.proprietorId + "_" + fkId;
      }
      else{
        return;
      }
      var that = this;
      list.loadCategories(0, (content)=> {
        that.initCategory(content)
      });
    },
    filterCategory(firstCatgeory,allCateogry){
      if (firstCatgeory.length == allCateogry.length) return allCateogry;
      let categoryIds=[];
      firstCatgeory.map((item)=>{
        categoryIds.push(item.Id);
      });
      allCateogry= allCateogry.filter((item) => categoryIds.indexOf(item.Id)>-1);
      return allCateogry;
    },
    /**
    * 加载目录信息 
    * */
    loadCategoryinfo(callback) {
      var that = this;
      let { cid}=this.data;
      list.loadCategoryinfo(cid, (content) => {
        this.setData({
          priceRange: content.PriceRange||[]
        })
      });
      if (cid == 0) {
        callback(); 
        return;
      }
      //取缓存中的分类数据
      // category.load(app.dns.proprietorId, app.dns.proprietor, 0, (res) => {
      //   let tree = res.Content;
      //   let obj=tree.filter((item) => item.Id == cid);
      //   this.setData({
      //     priceRange: obj&&obj.length>0?obj[0].PriceRange:[]
      //   });
      //   callback();
      // });
    },
    /**
     * 初始化分类
     */
    initCategory(firstCatgeory) {
      let that = this;
      let { selectedCategoryId}=this.data;
      selectedCategoryId = Number(that.data.cids);
      category.load(app.dns.proprietorId, app.dns.proprietor, 0, (res) => {
        let tree = that.filterCategory(firstCatgeory,res.Content);
        //分类
        let layer = 0;
        that.data.tree=tree;
        let obj = that.get_node_by_cid(that, selectedCategoryId);
        if (obj != null) {
          layer = obj.layer;
          that.setData({
            typeId: obj.category.TypeId
          })
        }
        if (selectedCategoryId&& layer) { 
          //设置节点是否展开
          that.set_current_node_isopen(that, layer, selectedCategoryId);
        }
        //设置父级节点选中状态
        that.set_node_parent_selected(that, selectedCategoryId);
        let img = tree.filter(item => {
          return item.CateImg
        })
        img = img.map(item => {
          return item.CateImg
        })
        that.setData({
          cid: Number(that.data.cids)?Number(that.data.cids):that.data.cid,//that.data.cid
          tree: that.data.tree,
          categoryIconList: img
        });
        if (that.filterComponent != null) {
          that.filterComponent.setData({
            typeId: that.data.typeId || that.data.types,
            bid: that.data.bid,
            tag:that.data.tag,
            vid:that.data.vid
          });
          this.filterComponent.get_category_screens();
        }
      },true);
    

    },

    /**
     * 获得要请求的参数
     */
    get_param() {
      let { PageIndex, PageSize, keywords, sortField,sortDirect, cid, bid, tag, rule_id, tag_id, minprice, minToPrice, extattrs, enableZeroStockBuy, customAttrs, isShowZeroStock, addr, cids, vid, ikcqr,NotShowProductNoneOffered}=this.data;
      // 隐藏无货商品时，不显示库存不足的商品
      if (NotShowProductNoneOffered) {
        isShowZeroStock = 0
      } else {
        // 允许0库存下单时，显示库存不足的商品
        if (enableZeroStockBuy) {
          isShowZeroStock = 1
        }
      }
      return {
        PageIndex: PageIndex,
        PageSize: PageSize,
        keywords: keywords,
        sortField: sortField,
        sortDirect: sortDirect,
        cid:Number(cids)?cids:cid,
        bid: bid,
        vid:vid,
        tag:tag,
        rule_id: rule_id,
        tag_id: tag_id,
        minprice: minprice,
        minToPrice:minToPrice,
        extattrs: extattrs,
        isShowZeroStock: isShowZeroStock,
        customAttrs:customAttrs||'',
        areaCode:addr.code,
        ikcqr: ikcqr
      };
    },
    /**加载商品列表 */
    loadProductList(callback) {
      var that = this;
      let param=that.get_param();
      //设置签名（如果签名相同，则不进行加载）
      that.data.sigin = that.getSiginData();
      let pageNeedScroll = true
      list.loadProductList(param,function (res, isCache) {
        let contentlistTem = unrealData.goodsList
        if (that.data.PageIndex == 1) {
          contentlistTem = [];
          pageNeedScroll = false
        }
        if (res.Content.TotalCount > 0) {
          var contentlist = res.Content.Data;
          var totalPage = res.Content.TotalPage;
          var hasMoreData = res.Content.TotalCount > (that.data.PageIndex) * that.data.PageSize;
          var index = contentlistTem.length;
          let PageIndex = that.data.PageIndex
          let PageSize = that.data.PageSize
          for(var i = 0;i < contentlist.length; i++){
            var goodsItem = contentlist[i];
            //这里需要把原始值用另一个字段存下来，方便后面计算时用原始值计算
            goodsItem.SBuyLowerLimit = goodsItem.BuyLowerLimit || 0;
            goodsItem.SBuyUpperLimit = goodsItem.BuyUpperLimit || 0;
            goodsItem.SStock = goodsItem.Stock;
            if(goodsItem.IsSingle == 1){
              that.unitList(goodsItem.AuxiliaryUnits,goodsItem.UnitPrices,goodsItem.CartCount,goodsItem)
            }
            goodsItem.show = false;
            goodsItem.longListIndex = (PageIndex - 1) * PageSize + i
            // 将默认单位复制给商品中，用于标签时使用
            let AuxiliaryUnits = goodsItem.AuxiliaryUnits || []
            let defaultIndex = AuxiliaryUnits.findIndex((item) => {
              return item.IsDefaultUnit == 1
            })
            if (defaultIndex != -1) {
              goodsItem.DefaultUnit = AuxiliaryUnits[defaultIndex].DefaultUnit || AuxiliaryUnits[defaultIndex].Name || ''
              // 默认销售单位非基础单位，并且之前没有加过此商品进购物车
              // 要将zIndex改为销售单位的下标
              if (isEmpty(goodsItem.ZIndex)) {
                goodsItem.ZIndex = defaultIndex
              }
            }
          }
          var goodlist = contentlistTem.concat(contentlist);
          //先填充页面
          unrealData.setData({
            goodsList: goodlist
          })
          unrealData.latestData(that, pageNeedScroll)
          that.setData({
            // goodsList: goodlist,
            hasMoreData: hasMoreData,
            // isLoadComplete: true,
            time:new Date().getTime()
          });
 
          if (!isCache){
            if (callback && typeof (callback) == "function") {
              callback(goodlist, that.data.PageIndex);
            }
            that.loadProductActivities(that, contentlist, index);
          }
         
        } else {
          unrealData.setData({
            goodsList: []
          })
          that.setData({
            goodsList: [],
            hasMoreData: true,
            isLoadComplete:true,
            PageIndex: 1
          },()=>{
            if (callback && typeof (callback) == "function") {
              callback([], that.data.PageIndex);
            }
          });
        }
      });
    },
    bindUnfold(e){
      var that = this;
      var index = e.currentTarget.dataset.index;
      let {
        goodsList
      } = unrealData
      goodsList[index].show = !goodsList[index].show;
      let pageGoodsList = this.data.goodsList
      unrealData.setData({
        goodsList
      })
      let pageIndex = pageGoodsList.findIndex(item => item.longListIndex == goodsList[index].longListIndex)
      if (pageIndex == -1) {
        return
      }
      pageGoodsList[pageIndex] = goodsList[index]
      this.setData({
        goodsList
      })
    },
    unitList(AuxiliaryUnits,UnitPrices,CartCount,goodlist){
      let { quantityDigits } = this.data;
      for(var i=0;i<AuxiliaryUnits.length;i++){
        var item = AuxiliaryUnits[i];
        var t = detail.parseRule(UnitPrices, item.Translated, item.Qty || 0, false);
        // var t = detail.parseRule(UnitPrices, item.Translated,item.Qty==0?goodlist.Stock==0?item.Qty:1:item.Qty, false);
        if(t.has){
          item.price = t.price;
          if(t.integral){
            item.integral = t.integral;
          }
        }
        var otherAuxiliaryUnits = AuxiliaryUnits.filter(unit=>{return unit.Translated != item.Translated});
        var otherUnitQuantity = 0;
        if (otherAuxiliaryUnits&&otherAuxiliaryUnits.length>0) {
            otherAuxiliaryUnits.map((child, idx) => {
                if (child.Qty!=undefined&&child.Qty>0) {
                    otherUnitQuantity += (child.Qty || 0) * (child.Translated || 1);
                }
            });
        }
        item.BuyLowerLimit = goodlist.SBuyLowerLimit > 0 && goodlist.SBuyLowerLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyLowerLimit - otherUnitQuantity, quantityDigits) : 0;
        item.BuyUpperLimit = goodlist.SBuyUpperLimit > 0 && goodlist.SBuyUpperLimit > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SBuyUpperLimit - otherUnitQuantity, quantityDigits) : 0;
        item.Stock = goodlist.SStock > 0 && goodlist.SStock > otherUnitQuantity ? util.keepDecimal("ceil", goodlist.SStock - otherUnitQuantity, quantityDigits) : 0;
        item.IsSingle = goodlist.IsSingle;
        item.DefaultUnit = item.Name;
        item.ZeroStockBuy = goodlist.ZeroStockBuy;
        item.SpecValue = goodlist.SpecValue;
        item.ProductId = goodlist.ProductId;
        item.DiscountId = goodlist.DiscountId;
        item.DiscountType = goodlist.DiscountType;
        AuxiliaryUnits[i] = item;
        if(this.data.GoodsUnitDisplayMode == 0&&item.Translated == (goodlist.Translated||goodlist.Radix)){
          goodlist.BuyLowerLimit = item.BuyLowerLimit;
          goodlist.BuyUpperLimit = item.BuyUpperLimit;
          goodlist.Stock = item.Stock;
        }
      }
    },
    loadProductActivities(that,contentlist,index){
      //加载促销信息
      let {
        hideActivity
      } = this.data
      activities.loadProductActivities(contentlist, this.data.hasMaket, this.data.rule_id, this.data.addr.code, function (source, index) {
        let {
          goodsList
        } = unrealData
        let len = goodsList.length
        for (var i = 0; i < source.length && index + i < len; i++) {
          goodsList[index + i] = source[i];
        }
        let obj = goodsList;
        obj.map((item)=>item.market = Array.from(new Set(item.market)));    //营销标识去重
        obj.map((item)=>item.Label = Array.from(new Set(item.Label))); //营销标识去重
        for(var i=0;i<obj.length;i++){
          if(obj[i].AuxUnit && obj[i].isPanic){
            obj[i].PanicGoods.map((p)=>{
              that.unitList(obj[i].AuxiliaryUnits,p.UnitPrices,obj[i].CartCount,obj[i])
            })
          }
        }
        //重新渲染
        unrealData.setData({
          goodsList: obj
        })
        unrealData.refreshGoodsList(that)
      }, index, hideActivity);
    },
    /**搜索 */
    bindSearch(e) {
      var that = this;
      clickIncrement(()=> {
        this.setData({
          vid:'',
          bid: "",
          tag:"",
          cid: 0,
          extattrs: "",
          minprice: "",
          priceRange : [],
          typeId : 0,
        })
        let {
          hasNav,
          isChangeSearchCriteria
        } = that.data
        // 如果用户没有修改过当前页面的分类等信息，搜索时重置掉之前搜索的分类等信息（相当于搜索全部商品）
        if (!isChangeSearchCriteria) {
          that.setData({
            cids: '',
            // tag_id: '',
            // rule_id: ''
          })
        }
        let component = that.selectComponent('#productSort')
        if (component) {
          if (isEmpty(e.detail)) {
            // 无关键词时搜索，默认综合排序
            that.setData({
              sortField: "sortorder",
              sortDirect: "desc",
            })
            component.reset()
          } else {
            // 有关键词时搜索，移除全部排序方式
            that.setData({
              sortField: "",
              sortDirect: ""
            })
            component.clear()
          }
        }
        let id = `#suggestion`
        let suggestion = this.selectComponent(id)
        suggestion.hide()
        suggestion.addKeyword(e.detail)
        that.setData({
          keywords: e.detail,
          PageIndex: 1
        })
        that.loadProductList();
      });
    },
    /**
     * 将排序重设为按综合排序
     */
    resetSort () {
      let component = this.selectComponent('#productSort')
      if (component) {
        component.reset()
      }
    },
    /**
     * 将排序重设为按综合排序
     */
    clearSort () {
      let component = this.selectComponent('#productSort')
      if (component) {
        component.clear()
      }
    },
    bindScan(){
      var that = this;
      if(!that.data.isScan){
        wx.scanCode({
          success: (res) => {
            that.bindSearch({
              detail: res.result
            })
          }
        })
      }else{
        this.triggerEvent('onScanCodeEvent','');
      }
    },
    onSearch(e){
      this.setData({
        keywords: e.detail
      })
    },
    /**排序 */
    bindSort(e) {
      var that = this;
      clickIncrement(function() {
        that.setData({
          PageIndex: 1,
          sortField: e.detail.sortField || "sortorder",
          sortDirect: e.detail.sortDirect || "DESC",
        });
        that.loadProductList();
      });
    },

    /*
    弹出缺货登记的层 
    */
    showScantyModal(e) {
      if (!authorize.isLogin('store')) {
        authorize.redirect('store');
        return;
      }
      var that = this;
      var idx = e.currentTarget.dataset.idx;
      let {
        goodsList
      } = unrealData
      var product = goodsList[idx];
      if (product.IsSingle == 0) {
        that.onShowGoodsModal({ detail: { product: product, idx: idx } });
      } else {
        // console.log(product,'=====product');
        let unit_index = 0;
        for (let k = 0; k < product.AuxiliaryUnits.length; k++) {
          if (product.AuxiliaryUnits[k].Name == product.AuxUnit) {
            unit_index = k;
            break;
          }
        }
        product.ZIndex = unit_index;
        if(product.EnableSKUTranslated!=1){
          let units = product.AuxiliaryUnits||[];
          product.productUnitText = detail.loadUnitContext(units, product.Unit);
        }
        console.log(product,'========scantyProduct')
        that.outofstock.setData({
          scantyProduct: product,
        })
        that.outofstock.openScanyDialog(e);
      }
    },
   
    showStockDistribution(e) {
      var idx = e.currentTarget.dataset.idx;
      let {
        goodsList
      } = unrealData
      var product = goodsList[idx];
      let promotionsLabel = product.promotionsLabel || []
      product.Label = promotionsLabel.map((item) => {
        return item.label
      })
      this.stockdistribution.setData({
        product: product,
      })
      this.stockdistribution.showStockModal(e);
    },

    /**判断是否登录 */
    isLogin() {
      if (!authorize.isLogin('store')) {
        authorize.redirect('store');
        return;
      }
    },


    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {
      wx.stopPullDownRefresh();
      let pageGoodsList = this.data.goodsList
      let {
        goodsList
      } = unrealData
      try {
        let item1 = goodsList[0]
        let item2 = pageGoodsList[0]
        if (!isEmpty(item2) && item1.longListIndex != item2.longListIndex) {
          return
        }
      } catch (error) {
        console.log(error);
      }
      this.data.PageIndex = 1;
      this.loadProductList();
      this.data.tabKey="";
      // this.loadFirstCategory();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
      let {
        cacheData
      } = unrealData
      let isBottom = unrealData.isBottom(this)
      if (!isBottom) {
        return
      }
      if (this.data.hasMoreData) {
        this.data.PageIndex += 1;
        let sigin = this.getSiginData();
        this.loadProductList((list, page_index) => {
          if (!cacheData[sigin])return;
          cacheData[sigin].list=list;
          cacheData[sigin].page_index=page_index;
          unrealData.setData({
            cacheData
          })
        });
      }
    },
    /**
     * 选择目录
     *  */
    selectedCategory(e,categoryid,level) {
      let pageSigin = this.data.pageSigin
      var that = this;
      that.data.cids = 0;
      var selectedCategoryId,layer,typeid;
      var o = e.currentTarget.dataset;
      selectedCategoryId = o.categoryid;
      layer = o.level;
      typeid = o.typeid;
      let btntype = o.btntype // 按钮类型，categorySubAll: 三级全部按钮
      let index = o.index // 当前点击项的下标
      clickIncrement(()=> {
        let isShowZeroStock = 0;
        let {
          cid,
          isScanty,
          enableZeroStockBuy,
          tree,
          activeOneCategory,
          activeTwoCategory,
          activeThreeCategory
        } = this.data;
        if (!enableZeroStockBuy && isScanty) {
          isShowZeroStock = 1;
        }
        activeOneCategory = Number(activeOneCategory)
        activeTwoCategory = Number(activeTwoCategory)
        activeThreeCategory = Number(activeThreeCategory)
        if (layer == 2 && !selectedCategoryId && !typeid) { // 点击全部时
          try {
            let item = {}
            if (activeTwoCategory != -1) { // 当选择二级分类，则点击全部显示二级分类下的全部数据
              item = tree[activeOneCategory].Children[activeTwoCategory]
            } else { // 未选择二级分类，则点击全部显示一级分类全部数据
              item = tree[activeOneCategory]
            }
            selectedCategoryId = item.Id || 0
            typeid = item.TypeId || 0
          } catch (e) {
            // 选择错误，或者未选择一级分类时，默认为全部商品
            selectedCategoryId = 0
            typeid = 0
          }
        }
        let categoryTopId = '' // 横向一级目录scroll-id
        let categorySubId = '' // 横向三级目录scroll-id
        if (layer == 3 || btntype == 'categorySubAll') {
          // 点击三级按钮时，将滚动条滚动至对应的按钮
          if (btntype == 'categorySubAll') {
            categorySubId = 'sub_all'
          } else {
            categorySubId = `sub_item_${index}`
          }
        } else {
          categorySubId = 'sub_all'
          if (layer == 1 || btntype == 'categoryTopAll') {
            // 点击一级按钮时，将滚动条滚动至对应的按钮
            if (btntype == 'categoryTopAll') {
              categoryTopId = 'top_all'
            } else {
              categoryTopId = `top_item_${index}`
            }
          }
        }
        if (layer != 3) {
          //设置节点是否展开
          that.set_current_node_isopen(that, layer, selectedCategoryId);
        }
        //设置父级节点选中状态
        that.set_node_parent_selected(that, selectedCategoryId);
        if (cid == selectedCategoryId){
          that.setData({
            tree: that.data.tree,
            oneCategoryExpand: false,
            threeCategoryExpand: false
          });
          return;
        }
        else{
          that.setData({
            bid: "",
            tag:"",
            extattrs: "",
            // isShowZeroStock: isShowZeroStock,
            minprice: "",
            cid: selectedCategoryId,
            tree: that.data.tree,
            oneCategoryExpand: false,
            threeCategoryExpand: false
          });
        }
        that.setData({
          categoryTopId,
          categorySubId,
          isChangeSearchCriteria: true
        })     
        //设置当前的价格区间
        var obj = that.get_node_by_cid(that, selectedCategoryId);

        var priceRange = obj == null ? [] : (obj.category.PriceRange || []);
        if (obj != null) {
          that.data.priceRange = priceRange;
          that.data.typeId = obj.category.TypeId;
        } 
        else{
          that.data.priceRange = [];
          that.data.typeId = 0;
        }
        that.filterComponent.setData({
          cid: selectedCategoryId,
          typeId: that.data.typeId,
          priceRange: that.data.priceRange,
        })
        that.filterComponent.get_category_screens();
        let sigin = that.getSiginData();
        let {
          cacheData
        } = unrealData
        if (!isEmpty(cacheData[pageSigin])) {
          cacheData[pageSigin].cacheList = that.data.goodsList
        }
        if (that.isCacheCategory(sigin)) return;
        //重新加载页面
        that.data.PageIndex = 1;
        that.loadProductList((list,page_index)=>{
          cacheData[sigin]={
            list : list,
            time : new Date().getTime(),
            scrollTop : 0,
            page_index:page_index
          }
          this.triggerEvent("onPageScrollTo", {
            scrollTop: 0
          });
          unrealData.setData({
            cacheData
          })
        });
      });

    },
    /**
     * 是否有分类缓存
     */
    isCacheCategory(sigin){
      let {
        cacheData
      } = unrealData
      let that=this;
      let keys = Object.keys(cacheData);
      if (keys.length>0&&keys.indexOf(sigin)>-1) {
        let obj = cacheData[sigin];
        let list = []
        if (!isEmpty(cacheData[sigin].cacheList)) {
          list = cacheData[sigin].cacheList
        } else if (!isEmpty(cacheData[sigin].list)) {
          list = cacheData[sigin].list
        }
        var goodsList = list;
        if (list.length > 0 && GoodsNumCache.compareTime(obj.time)){         
          for (var i = 0; i < goodsList.length; i++) {
            goodsList[i].CartCount = GoodsNumCache.getProductNum(goodsList[i].ProductId, goodsList[i].CartCount,goodsList[i].IsSingle==1);
          }
   
        }
        that.data.sigin = sigin;
        that.data.PageIndex = obj.page_index;
        unrealData.setData({
          goodsList: goodsList
        })
        that.setData({
          goodsList: goodsList
        });
        this.triggerEvent("onPageScrollTo", {
          scrollTop: obj.scrollTop
        });
        return true;
      }
    },
    /**
     * 设置滚动位置
     */
    setScollTop: debounce(function (scrollTop) {
      let {
        cacheData
      } = unrealData
      let sigin = this.getSiginData();
      let keys = Object.keys(cacheData);
      if (keys.length > 0 && keys.indexOf(sigin) > -1) {
        let obj = cacheData[sigin];
        obj.scrollTop = scrollTop;
        cacheData[sigin] = obj
        unrealData.setData({
          cacheData
        })
      }
      unrealData.onPageScroll(scrollTop, this)
    }, 500),
    /**
     * 设置节点是否展开
     */
    set_current_node_isopen(that, layer, selectedCategoryId) {
      let activeOneCategory = -1 // 当前活动的一级分类
      let activeTwoCategory = -1 // 当前活动的二级分类
      let activeThreeCategory = -1 // 当前活动的三级分类
      for (var i in that.data.tree) {
        var first = that.data.tree[i];
        //父级是否选中
        first.parentselected = false;
        if (selectedCategoryId == first.Id) {
          first.isopen = first.isopen == true ? false : true;
          that.setData({
            scrollTop: i>0?(i + 1) * 5:0
          })
          activeOneCategory = i
          // 重置二级目录的被选中状态
          for (var j in (first.Children || [])) {
            var second = first.Children[j];
            second.parentselected = false;
          }
        } else {
          first.isopen = false;
          for (var j in (first.Children || [])) {
            var second = first.Children[j];
            second.parentselected = false;
            if (selectedCategoryId == second.Id) {
              first.isopen = true;
              second.isopen = second.isopen == true ? false : true;
              first.parentselected = true;
              activeOneCategory = i
              activeTwoCategory = j
            } else {
              second.isopen = false;
              for (var k in (second.Children || [])) {
                if (selectedCategoryId == second.Children[k].Id) {
                  first.isopen = true;
                  second.isopen = true;
                  first.parentselected = true;
                  second.parentselected = true;
                  activeOneCategory = i
                  activeTwoCategory = j
                  activeThreeCategory = k
                }
              }
            }
          }
        }
      }
      this.setData({
        activeOneCategory,
        activeTwoCategory,
        activeThreeCategory
      })
    },
    /**
     * 设置父级节点选中状态
     */
    set_node_parent_selected(that, selectedCategoryId) {
      for (var i in that.data.tree) {
        var first = that.data.tree[i];
        if (selectedCategoryId == first.Id) {
          break;
        }
        for (var j in first.Children) {
          var second = first.Children[j];
          if (selectedCategoryId == second.Id) {
            first.parentselected = true;
            break;
          }
          for (var k in second.Children) {
            if (selectedCategoryId == second.Children[k].Id) {
              second.parentselected = true;
              break;
            }
          }
        }
      }
    },
    /**
     * 获得节点
     *  */
    get_node_by_cid(that, selectedCategoryId) {
      for (var i in that.data.tree) {
        var first = that.data.tree[i];
        if (selectedCategoryId == first.Id) {
          return {
            category: first,
            layer: 1
          };
        }
        for (var j in first.Children) {
          var second = first.Children[j];
          if (selectedCategoryId == second.Id) {
            return {
              category: second,
              layer: 2
            };
          }
          for (var k in second.Children) {
            if (selectedCategoryId == second.Children[k].Id) {
              return {
                category: second.Children[k],
                layer: 3
              };
            }
          }
        }
      }
      return null;
    },
    /**
     * 点击帅选
     */
    onFilterEvent(e) {
      // this.filterComponent.get_category_screens();
      // this.filterComponent.reset();
      this.setData({
        showFilter: true
      });
    },
    /**
     * 筛选确定
     */
    onFilterComfirmEvent(e) {
      var dic = e.detail;
      dic.PageIndex = 1;
      this.setData(dic);
      this.setData({
        customAttrs:dic.customAttrs,
        minToPrice:dic.minToPrice+','+dic.maxPrice,
        isChangeSearchCriteria: true
      })
      this.shutFilter();
      this.loadProductList();
    },
    /**
     * 关闭筛选
     */
    shutFilter: function() {
      this.setData({
        showFilter: false
      });
    },
    onImageLoadError() {
      var that = this;
      that.setData({
        pic: "/assets/images/img.png"
      })
    },
    /**显示多规则 */
    onShowGoodsModal(e) {
      var that = this;
      e = e.detail;
      let { addr, priceDigits, decimalDigits, quantityDigits, isScanty, hasMaket } = this.data;
      that.fasterComponent.setData({
        item: e.product,
        isScanty: isScanty,
        quantityDigits: quantityDigits,
        priceDigits: priceDigits,
        decimalDigits: decimalDigits,
        areaCode: addr.code,
        hasMaket: hasMaket,
        addCompleted: function (goods) {
          that.onAddCartCompleted({ detail: { product: goods, idx: e.idx} });
        }
      });
      // that.fasterComponent.readHeight()
      that.fasterComponent.onShowGoodsModal(e);
    },
    /**
     * 加入完成后调用，更新界面显示数量
     */
    onAddCartCompleted(e) {
      e = e.detail;
      let goodsList = this.data.goodsList
      let index0 = goodsList.findIndex((item) => {
        return item.ProductId == e.product.ProductId
      })
      if (index0 != -1) {
        goodsList[index0] = e.product
      }
      let goodsList1 = unrealData.goodsList
      let index1 = goodsList1.findIndex((item) => {
        return item.ProductId == e.product.ProductId
      })
      if (index1 != -1) {
        goodsList1[index1] = e.product
        unrealData.setData({
          goodsList: goodsList1
        })
      }
      this.setData({
        goodsList
      });
    },

    toDetail(e) {
      var pagetype = e.currentTarget.dataset.pagetype;
      var linkparam = e.currentTarget.dataset.linkparam;
      var loadcomplate = e.currentTarget.dataset.loadcomplate;
      if (this.data.hasMaket) {
        pagetype=0;
        linkparam = "productId=" + e.currentTarget.dataset.id + "&id=" + e.currentTarget.dataset.id
      }
      if (loadcomplate != 1) return;
      var url = "productDetail";
      if (pagetype == 1 || pagetype == 2) {
        url = "groupDetail";
      }
      theme.routerTo(url, linkparam);

    },
    showDelivery(e){
      this.deliveryComponent.loadAdressList(e);
    },
    /**
     * 配送至弹层选择地址
     */
    selectedAdress(e){
      let that=this;
      this.data.PageIndex = 1;

      this.setData({
        addr: { area: e.detail.Area, code: e.detail.Code}
      },()=>{
        let {
          cacheData
        } = unrealData
        let sigin = that.getSiginData();
        this.loadProductList((list,page_index)=>{
           cacheData[sigin] = {
             list: list,
             time: new Date().getTime(),
             scrollTop: 0,
             page_index:page_index
           }
           unrealData.setData({
            cacheData
           })
           that.completeCallBack();
         });
      })
    },
    onUnload(){
      clearTimer();
      unrealData.reset()
    },
    completeCallBack() {
      let { proprietorId}=this.data;
       if (proprietorId != app.dns.proprietorId){
         proprietorId = app.dns.proprietorId;
         this.loadCategoryinfo(()=>{
           this.filterComponent.get_category_screens();
         });

      }
      this.data.proprietorId = proprietorId;
    },
    /**
   * 切换样式
   */
    switchView() {
      let { showStyle}=this.data;
      this.setData({
        showStyle: showStyle=='line'?'view':'line',
        thumb: showStyle == 'line' ? 300 : 200
      })
      storage.put('showStyle',showStyle=='line'?'view':'line')
      // console.log(storage.get('showStyle'),'=====');
    },
    /**
     *  当有侧边栏时,只显示为横向一行模式
     */
    setLineMode () {
      if (this.data.hasNav && this.data.showStyle == 'view') {
        this.setData({
          showStyle: 'line',
          thumb: 300
        })
      }
    },
    onPageScroll(e){
      console.log(e,'=========detail');
    },
    bindLabel(e){
      var id = e.currentTarget.dataset.id;
      router.navigate({
        path:"promotionDetail",
        params:{
          id:id
        }
      })
    },
    getUnrealData () {
      return unrealData
    },
    /**
     * 顶部搜索框获取焦点
     */
    searchFocus() {
      let id = `#suggestion`
      let component = this.selectComponent(id)
      component.show()
    },
    /**
     * 点击 历史/推荐 中的内容搜索
     * @param {*} e 
     */
    suggestionSearch(e) {
      this.bindSearch({
        detail: e.detail.keyword
      })
    },
    /**
     * 切换三级分类横向滚动还是展开展示
     */
    toggleCategory (e) {
      let key = e.currentTarget.dataset.key
      let value = this.data[key]
      this.setData({
        [key]: !value
      })
    },
    /**
     * 设置目录侧边栏等固定内容的信息
     */
    setAsideViewInfo: debounce(async function() {
      let that = this
      let isIphoneX = this.data.isIphoneX
      let AppQuickTemplateConfig = this.data.AppQuickTemplateConfig || {}
      let templateIndex = AppQuickTemplateConfig.TemplateIndex || 0
      let DisplayClassification = AppQuickTemplateConfig.DisplayClassification || 0
      let hasNav = this.data.hasNav || false
      let inFast = this.data.inFast
      let tree = this.data.tree || []
      let activeOneCategory = this.data.activeOneCategory
      let activeTwoCategory = this.data.activeTwoCategory
      let systemInfo = getSystemInfoSync()
      let menuHeight = 80 // 快速下单顶部目录切换高度
      let searchHeight = 110 // 搜索框栏高度
      let categoryTopHeight = 182 // 横向一级分类高度
      let categorySubHeight = 72 // 横向三级分类高度
      let sortHeight = 104 // 三级分类下面的排序栏高度
      let tabbarHeight = 100 // 底部导航栏高度
      let defaultSortHeight = 0 // 默认的排序栏高度
      try {
        // 获取页面内容节点信息，重新设置高度
        let res = await Promise.all([getViewSize('#header', this), getViewSize('#category-v1-top .collapsible', this), getViewSize('#category-v1-sub .collapsible', this)], getViewSize('#productSort', this))
        if (Array.isArray(res[0])) {
          if (!isEmpty(res[0][0]) && Array.isArray(res[0][0])) {
            let height = res[0][0][0].height * systemInfo.rpxRate
            searchHeight = height // 搜索栏高度
          }
        }
        if (Array.isArray(res[1])) {
          if (!isEmpty(res[1][0]) && Array.isArray(res[1][0])) {
            let height = res[1][0][0].height * systemInfo.rpxRate
            categoryTopHeight = height // 一级菜单栏高度
          }
        }
        if (Array.isArray(res[2])) {
          if (!isEmpty(res[2][0]) && Array.isArray(res[2][0])) {
            let height = res[2][0][0].height * systemInfo.rpxRate
            categorySubHeight = height // 三级菜单栏高度
          }
        }
        if (Array.isArray(res[3])) {
          if (!isEmpty(res[3][0]) && Array.isArray(res[3][0])) {
            let height = res[3][0][0].height * systemInfo.rpxRate
            sortHeight = height // 排序栏高度
          }
        }
      } catch (error) {
        
      }
      if (!inFast) { // 非快速下单,不显示顶部目录切换
        menuHeight = 0
      }
      // else { // 快速下单页面，只有默认样式
      //   templateIndex = 0
      // }
      if (templateIndex == 3 || !hasNav) { // 第三种样式,不单独显示一级分类
        categoryTopHeight = 0
      }
      if (templateIndex == 1 || !hasNav) { // 第一种样式,不单独显示三级分类
        categorySubHeight = 0
      }
      if (templateIndex == 0) { // 默认样式，不单独显示一级/三级分类
        categoryTopHeight = 0
        sortHeight = 0
        defaultSortHeight = 104
        categorySubHeight = 0
      }
      if (isIphoneX) {
        tabbarHeight = 130
      }
      try {
        // 三级目录为空时不显示横向三级目录高度
        if (tree[activeOneCategory].Children[activeTwoCategory].Children.length == 0) {
          categorySubHeight = 0
        }
      } catch (error) {
        categorySubHeight = 0
      }
      let asideTop = menuHeight + defaultSortHeight + searchHeight + categoryTopHeight
      let asideHeight = systemInfo.rpxHeight - asideTop - tabbarHeight
      let contentPaddingTop = searchHeight + defaultSortHeight + categoryTopHeight + categorySubHeight + sortHeight
      let topExpandHeight = systemInfo.rpxHeight - menuHeight - searchHeight - tabbarHeight
      let subExpandHeight = asideHeight
      let searchTop = menuHeight
      console.log({
        style: {
          menuHeight,
          searchHeight,
          categoryTopHeight,
          asideHeight,
          asideTop,
          searchTop,
          contentPaddingTop,
          topExpandHeight,
          subExpandHeight,
          rpxHeight: systemInfo.rpxHeight,
          tabbarHeight,
          categorySubHeight,
          sortHeight,
          AppQuickTemplateConfig,
          inFast,
          hasNav,
          defaultSortHeight
        }
      })
      this.setData({
        style: {
          asideHeight,
          asideTop,
          searchTop,
          contentPaddingTop,
          topExpandHeight,
          subExpandHeight
        },
        showSort: true
      })
    }, 1000),
    /**
     * 阻止默认事件
     */
    nothing () {
      return false
    }
  },
})

// 获取元素属性
let getViewSize = (selector = '', that) => {
  return new Promise((resolve, reject) => {
    that.createSelectorQuery().selectAll(selector).boundingClientRect().exec((res) => {
      resolve(res)
    })
  })
}